package com.zkadmin.controller;

import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.zkadmin.constraints.EmailConstraint;
import com.zkadmin.constraints.MobileConstraint;
import com.zkadmin.entity.SysUser;
import com.zkadmin.service.SysUserService;
import com.zkadmin.util.AdminConstants;

@SuppressWarnings("serial")
public class CreateUserDialogCtrl extends BaseCtrl<Window> {

	@WireVariable
	private SysUserService sysUserService;

	@Wire
	private Window win;
	@Wire
	private Textbox username;
	@Wire
	private Textbox password;
	@Wire
	private Textbox name;
	@Wire
	private Textbox email;
	@Wire
	private Textbox mobile;

	@Override
	protected void init(Window win) {
		this.win = win;
		email.setConstraint(new EmailConstraint());
		mobile.setConstraint(new MobileConstraint());
	}

	@Listen("onClick=#cancelBtn")
	public void closeDialog(Event e) {
		win.onClose();
	}

	@Listen("onClick=#okBtn")
	public void createUser(Event e) {
		if (sysUserService.findByUsername(username.getValue()) != null) {
			throw new WrongValueException(username, "【" + username.getValue() + "】已经存在。");
		}

		if (sysUserService.findByName(name.getValue()) != null) {
			throw new WrongValueException(name, "【" + name.getValue() + "】已经存在。");
		}

		SysUser user = new SysUser();
		user.setUsername(username.getValue());
		user.setName(name.getValue());
		user.setPassword(password.getValue());
		user.setEmail(email.getValue());
		user.setMobile(mobile.getValue());
		sysUserService.save(user);
		Events.postEvent(AdminConstants.EVENT_ONREFRESH, win, null);
		win.onClose();
	}

}
